/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.msstudio.message;

import com.msstudio.utils.MD5;
import com.msstudio.websocket.client.WebSocketClient;
import com.msstudio.websocket.client.exception.WebSocketException;
import net.jarlehansen.protobuf.javame.ByteString;

/**
 *
 * @author sunnyz
 */
public class MessageSender {
    private final static String SERVER_URL = "http://localhost:8787";
    private final static String WEBSOCKET_PATH = "/websocket";
    
    private WebSocketClient webSocketClient = null;
    public static MessageHandler messageHandler;
    private boolean bIsLogined = false;
    
    public MessageSender()
    {     
        webSocketClient = new WebSocketClient();
        messageHandler = new MessageHandler();
        messageHandler.initialize(webSocketClient);
    }    
        
    
    public boolean sendLoginMessage(String username, String password)
    {
        connect();
        String md5Password = MD5.toMD5(password);
        Login login = Login.newBuilder().setUsername(username).setPassword(md5Password).build();
        byte[] loginBytes = null;
        Msg msg = null;
        try {
            loginBytes = login.toByteArray();
            msg = Msg.newBuilder().setMsgHead("Login").    // MsgHead必须为"Login",服务器端根据该字符串构造相应的handler name- "LoginHandler"
                setMsgBody(ByteString.copyFrom(loginBytes, 0, loginBytes.length)).
                build();    
            sendAMessage(msg);            
        } catch (Exception ex)
        {
            return false;
        } 
        finally {  // 必须要有finally, 同时要释放所用的内存
            md5Password = null;
            login = null;
            loginBytes = null;
        }
        return true;
    }
    
    public boolean connect()
    {
        if (webSocketClient.isConnected()) {
            return true;
        }
        try {
            webSocketClient.open(SERVER_URL, WEBSOCKET_PATH);
        } catch (WebSocketException ex) {
            return false;
        }
        return true;
    }
    
    public void abort()
    {
        this.webSocketClient.close();
    }
    
    private boolean sendAMessage(Msg msg)
    {
        if (webSocketClient == null) {
            return false;
        }
        try {
            webSocketClient.send(msg.toByteArray());
        } catch (Exception ex)
        {
            return false; //断线
        }
        finally {
            msg = null;
        }
        return true;
    }

}
